//
//  WISAppDelegate.m
//  upnpxdemo
//
//  Created by haiyong on 13-8-25.
//  Copyright (c) 2013年 wiimu.inc. All rights reserved.
//

#import "WISAppDelegate.h"
#import "RootViewController.h"
#import "ServerChooseViewController.h"
#import "ShowHomeMainViewController.h"
#import "MBProgressHUD.h"
#import "GlobalVar.h"
#import "wis.h"
#import "ArchiveCoderRomoteDevice.h"

@interface WISAppDelegate()
{

}

@end

@implementation WISAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //注册推送
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
//    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
//     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    application.applicationIconBadgeNumber = 0;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    CGRect frame = [[UIScreen mainScreen] bounds];
    
    if([[UIDevice currentDevice].systemVersion floatValue] >= 7) {
        [application setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    else {
        [application setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    }
    
    UIImage *image = [UIImage imageNamed:@"navigationbarback"];
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:0];
    [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
    if([[UINavigationBar appearance] respondsToSelector:@selector(setBarTintColor:)])
    {
        [[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
    }
//    NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0],
//                                 NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:20.0]};
//    [[UINavigationBar appearance] setTitleTextAttributes: attributes];
    
    if([[UIDevice currentDevice].systemVersion floatValue] >= 7){
        UIColor * tintColor = [UIColor colorWithRed:29.0/255.0
                                              green:173.0/255.0
                                               blue:234.0/255.0
                                              alpha:1.0];
        [self.window setTintColor:tintColor];
    }

    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)//iphone
    {
        if((int)frame.size.height == 568)
        {
            [GlobalInfo sharedInstance].deviceType = IPHONE4_TYPE;
        }
        else
        {
            [GlobalInfo sharedInstance].deviceType = IPHONE35_TYPE;
        }
    }
    else
    {
        [GlobalInfo sharedInstance].deviceType = IPAD_TYPE;
    }
    
    //RootViewController * root = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    
    //ServerChooseViewController * root = [[ServerChooseViewController alloc] initWithNibName:@"ServerChooseViewController" bundle:nil];
    
    
    [self restoreRemoteDeviceFromArchiveCoder];
    
    ShowHomeMainViewController *root = [[ShowHomeMainViewController alloc] initWithNibName:@"ShowHomeMainViewController" bundle:nil];
    
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:root];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
     
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[GlobalService sharedInstance] stopHTTPServer];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
    
    //[self storeArchiveCoder];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
 
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[GlobalService sharedInstance] startHTTPServer];
    [[GlobalService sharedInstance] checkIfIPChanged];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    

}

#pragma mark - Archive Coder
- (void)restoreRemoteDeviceFromArchiveCoder {
    
    [GlobalInfo sharedInstance].remoteArray = [NSMutableArray arrayWithCapacity:10];
    NSString *filePath = [GlobalVar getFilePath:@"remoteDeviceArray.plist"];
    
    NSMutableArray *archiveCoderList = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];//从文件读出
    for (ArchiveCoderRomoteDevice *coder in archiveCoderList) {
        
        wis_user_dev device;
        device.status = 0;//(int)coder.status;
        if (coder.uuid) {
            const char *uuid =[coder.uuid UTF8String];
            memcpy(device.uuid, uuid, 32);
        }
        if (coder.name) {
            const char *name =[coder.name UTF8String];
            memcpy(device.name, name, 32);
        }
        if (coder.bindTime) {
            const char *bindTime =[coder.bindTime UTF8String];
            memcpy(device.bind_time, bindTime, 20);
        }
        
        NSValue * value = [NSValue valueWithBytes:&device objCType:@encode(wis_user_dev)];
        [[GlobalInfo sharedInstance].remoteArray addObject:value];
    }
    
    NSLog(@"applicationWillEnterForeground %ld", [GlobalInfo sharedInstance].remoteArray.count);
}

- (void)storeArchiveCoder {
    
    NSString *filePath = [GlobalVar getFilePath:@"remoteDeviceArray.plist"];
    NSMutableArray *archiveCoderList = [[NSMutableArray alloc] init];
    for (NSValue *valObj in [GlobalInfo sharedInstance].remoteArray) {
        
        wis_user_dev device;
        [valObj getValue:&device];
        
        NSString *uuidStr = nil;
        NSString *nameStr = nil;
        NSString *bindTimeStr = nil;
        
        ArchiveCoderRomoteDevice *archiveCoder = [[ArchiveCoderRomoteDevice alloc] init];
        
        if (device.uuid) {
            
            uuidStr = [[NSString alloc] initWithCString:device.uuid encoding:NSUTF8StringEncoding];
            archiveCoder.uuid = uuidStr;
        }
        
        if (device.name) {
            
            nameStr = [[NSString alloc] initWithCString:device.name encoding:NSUTF8StringEncoding];
            archiveCoder.name = nameStr;
        }
        
        if (device.bind_time) {
            
            bindTimeStr = [[NSString alloc] initWithCString:device.bind_time encoding:NSUTF8StringEncoding];
            archiveCoder.bindTime = bindTimeStr;
        }
        
        archiveCoder.status = device.status;
        [archiveCoderList addObject:archiveCoder];
    }
    
    [NSKeyedArchiver archiveRootObject:archiveCoderList toFile:filePath];
    
    NSLog(@"applicationWillResignActive %ld", archiveCoderList.count);

}

#pragma mark - push notify
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog(@"My token is: %@", deviceToken);
    NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",deviceToken];
    deviceTokenStr = [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)];
    
    //    deviceTokenStr = [deviceTokenStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    {
        
        NSString *tt = [NSString stringWithFormat:@"%@",deviceToken];
        NSString *token = [[tt substringWithRange:NSMakeRange(1, [tt length]-2)]stringByReplacingOccurrencesOfString:@" " withString:@""];
        
     NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    [token writeToFile:[[url path] stringByAppendingPathComponent:@"token.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    
    [GlobalInfo sharedInstance].deviceToken = deviceTokenStr;
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    DLog(@"\napns -> didReceiveRemoteNotification,Receive Data:\n%@", userInfo);
    //把icon上的标记数字设置为0,
    application.applicationIconBadgeNumber = 0;
    
    if (userInfo && [userInfo objectForKey:@"aps"]) {
        NSDictionary *data = [userInfo objectForKey:@"aps"];
        NSString *alertMsg = [data objectForKey:@"alert"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:alertMsg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        
        //UINavigationController *navController = (UINavigationController *)self.window.rootViewController;
        //[navController.topViewController.view makeToast:alertMsg];
        

//        MBProgressHUD *_ProgressHUD = [[MBProgressHUD alloc] initWithView:self.window.rootViewController.view];
//        [self.window.rootViewController.view addSubview:_ProgressHUD];
//        _ProgressHUD.removeFromSuperViewOnHide = YES;
//        //_ProgressHUD.delegate = self;
//        _ProgressHUD.labelText = alertMsg;//  NSLocalizedString(@"LoginView_Loading", @"");
//        [_ProgressHUD show:YES];
//        [_ProgressHUD hide:YES afterDelay:2.0];
    }
    
    

}

@end
